package org.zfes.snowier.cloud.zbss.cms.words.service.impl;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.zfes.snowier.core.data.DataSet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.zfes.snowier.core.util.ZBeanUtil;
import org.zfes.snowier.core.util.ZDateUtil;
import org.zfes.snowier.core.util.ZAlert;
import org.zfes.snowier.core.util.ZAssert;
import org.zfes.snowier.common.dao.params.ParamMap;
import org.zfes.snowier.cloud.zbss.cms.words.service.ICmsWordsHistoryService;
import org.zfes.snowier.cloud.zbss.cms.words.service.ICmsWordsHotService;
import org.zfes.snowier.cloud.zbss.cms.words.service.ICmsWordsSearchService;
import org.zfes.snowier.cloud.zbss.cms.zconfig.ZConfig;
import org.zfes.snowier.cloud.zbss.cms.words.dao.CmsWordsHistoryMapper;
import org.zfes.snowier.cloud.zbss.cms.words.model.CmsWordsHistory;
import org.zfes.snowier.cloud.zbss.cms.words.model.CmsWordsHot;
import org.zfes.snowier.cloud.zbss.cms.words.model.CmsWordsSearch;

import java.util.stream.Stream;
@Service
public class CmsWordsHistoryServiceImpl implements ICmsWordsHistoryService{
 	@Autowired
	private CmsWordsHistoryMapper cmsWordsHistoryMapper;
	private ICmsWordsSearchService iCmsWordsSearchService; 
	private ICmsWordsHotService iCmsWordsHotService;
	@Transactional(rollbackFor=Exception.class)
 	@Override
	public void createCmsWordsHistory(CmsWordsHistory cmsWordsHistory) {
		ZBeanUtil.setCreateInfo(cmsWordsHistory);
		ZBeanUtil.validateBean(cmsWordsHistory);
		//插入到搜索表中--查找是否已有，
		String words=cmsWordsHistory.getWords().trim();//去掉首尾空格
		Optional<CmsWordsSearch> cmsWordsSearchOps=iCmsWordsSearchService.selectCmsWordsSearchByWords(words);
		if(cmsWordsSearchOps.isPresent()) {//已存在该关键字，则修改搜索次数
			CmsWordsSearch cmsWordsSearch=iCmsWordsSearchService.selectCmsWordsSearchByWords(words).get();
			cmsWordsSearch.setSiteId(cmsWordsHistory.getSiteId());
			cmsWordsSearch.setSearchCount(cmsWordsSearch.getSearchCount()+1);
			iCmsWordsSearchService.createCmsWordsSearch(cmsWordsSearch);
			//若搜索次数超过定值，则添加至热词表
			int hotWordsSearchRate=ZConfig.hotWordsSearchRate;//系统预定义热词的最低点击次数
			int hotWordsSearchInDays=ZConfig.hotWordsSearchInDays;//系统预定义热词有效时间
			if(cmsWordsSearch.getSearchCount()>=hotWordsSearchRate) {
				//先检查该热词是否已有
				String words1=cmsWordsSearch.getWords();
				Optional<CmsWordsHot> cmsWordsHotOps=iCmsWordsHotService.selectByWords(words1);
				if(!cmsWordsHotOps.isPresent()) {//该热词不存在，添加之前先判断是否在设定时间内
					//时间判断
					LocalDate today=LocalDate.now();
					Date createDate=cmsWordsSearch.getCreateTime();
				    Instant createDateInstant = createDate.toInstant();
				    ZoneId zone = ZoneId.systemDefault();
				    LocalDateTime localDateTime = LocalDateTime.ofInstant(createDateInstant, zone);
				    LocalDate createDateLocal= localDateTime.toLocalDate();
					Period p = Period.between(today,createDateLocal);
					if(p.getDays()<=hotWordsSearchInDays) {//在预定时间内
						CmsWordsHot cmsWordsHot=new CmsWordsHot();
						cmsWordsHot.setWords(words1);
						cmsWordsHot.setSearchCount(cmsWordsSearch.getSearchCount());
						cmsWordsHot.setSiteId(cmsWordsSearch.getSiteId());
						iCmsWordsHotService.createCmsWordsHot(cmsWordsHot);
					}
				}
				else {//该热词已存在 更新搜索次数
					CmsWordsHot cmsWordsHot1= cmsWordsHotOps.get();
					cmsWordsHot1.setSearchCount(cmsWordsHot1.getSearchCount()+1);
					iCmsWordsHotService.updateCmsWordsHot(cmsWordsHot1);
				}
			}
		}
		else {//创建一条搜索词记录
			CmsWordsSearch cmsWordsSearch1=new CmsWordsSearch();
		    cmsWordsSearch1.setWords(words);
			iCmsWordsSearchService.createCmsWordsSearch(cmsWordsSearch1);
		}
		cmsWordsHistoryMapper.insertSelective(cmsWordsHistory);
	}
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public Optional<CmsWordsHistory> loadCmsWordsHistoryById(Long id) {
		if(id!=null){
			return Optional.ofNullable(cmsWordsHistoryMapper.selectByPrimaryKey(id));
		}
		return Optional.empty();
		
	}
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void updateCmsWordsHistory(CmsWordsHistory cmsWordsHistory) {
		ZBeanUtil.validateBean(cmsWordsHistory);
		cmsWordsHistory.setUpdateTime(ZDateUtil.newDate());
		cmsWordsHistoryMapper.updateByPrimaryKeySelective(cmsWordsHistory);
	}
	
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void deleteCmsWordsHistory(Long id) {
		ZAssert.notNull(id, "请选择要操作的数据");
		cmsWordsHistoryMapper.updateStatus(id, Byte.valueOf("-1"),ZDateUtil.newDate());
	}
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void setCmsWordsHistoryStatus(Long id, Byte status) {
		ZAssert.notNull(id, "请选择要操作的数据");
		ZAssert.notNull(status, "状态参数错误");
		if(!Stream.of(new Byte[] {-1,0,1}).anyMatch(val->val.equals(status))) {
			ZAlert.serviceLogicalError("状态参数错误");
		}
		cmsWordsHistoryMapper.updateStatus( id,  status,ZDateUtil.newDate()) ;
	}
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public DataSet loadCmsWordsHistoryDataSet(Map<String, Object> params) {
		ParamMap pm=ParamMap.filterParam(params);
		DataSet ds=DataSet.newDS2(cmsWordsHistoryMapper.selectListCount(pm), cmsWordsHistoryMapper.selectMapListPage(pm));
		return ds;
	}
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	//用户:查看用户搜索历史记录
	public List<CmsWordsHistory> loadCmsWordsHistoryByUserId(Long userId) {
		List<CmsWordsHistory> cmsWordsHistoryList=cmsWordsHistoryMapper.loadCmsWordsHistoryByUserId(userId);
		return cmsWordsHistoryList;
	}
	@Transactional(rollbackFor=Exception.class)
	@Override
	//用户：清空用户历史记录
	public void clearCmsWordsHistoryByUserId(Long userId) {
		cmsWordsHistoryMapper.updateStatusByUserId(userId, Byte.valueOf("-1"),ZDateUtil.newDate());
	}
}